package com.celan.year2023.month02.day01;

import java.util.HashMap;

public class Solution {
    public String decodeMessage(String key, String message) {
        HashMap<Character, Character> dic = new HashMap<>();
        char idx = 'a';
        for (char c : key.toCharArray()) {
            if (c == ' ') continue;
            if (!dic.containsKey(c)) dic.put(c, idx++);
        }
        StringBuilder res = new StringBuilder();
        for (char c : message.toCharArray()) {
            if (c != ' ') res.append(dic.get(c));
            else res.append(c);
        }
        return res.toString();
    }

    public String fractionToDecimal(int numerator, int denominator) {
        long num = (long) numerator;
        long den = (long) denominator;
        //没有小数
        if (num % den == 0) return String.valueOf(num / den);

        HashMap<Long, Integer> map = new HashMap<>();
        StringBuilder pre = new StringBuilder();
        //符号
        if ((num > 0 && den < 0) || (num < 0 && den > 0)) pre.append('-');
        num = num > 0 ? num : -num;
        den = den > 0 ? den : -den;
        //有小数
        //整数部分
        pre.append((int) (num / den)).append('.');

        //小数部分
        StringBuilder small = new StringBuilder();
        long remainder = num % den;
        int index = 0;
        while (remainder != 0 && !map.containsKey(remainder)) {
            map.put(remainder, index);
            remainder *= 10;
            small.append((int) (remainder / den));
            remainder %= den;
            index++;
        }
        //无限循环小数
        if(map.containsKey(remainder)){
            int idx = map.get(remainder);
            small.insert(idx,'(');
            small.append(')');
        }
        return pre.append(small).toString();
    }
}
